package com.wjpeng.wms.service.impl;

import com.wjpeng.wms.domain.Employee;
import com.wjpeng.wms.domain.Systemmenu;
import com.wjpeng.wms.mapper.SystemmenuMapper;
import com.wjpeng.wms.query.QueryObject;
import com.wjpeng.wms.query.SystemMenuQueryObject;
import com.wjpeng.wms.service.ISystemmenuService;
import com.wjpeng.wms.util.PageResult;
import com.wjpeng.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class SystemmenuServiceImpl implements ISystemmenuService {
    @Autowired
    private SystemmenuMapper systemmenuMapper;

    @Override
    public void saveOrUpdate(Systemmenu d) {
        if(d.getId() == null){
            systemmenuMapper.insert(d);
        }else{
            systemmenuMapper.updateByPrimaryKey(d);
        }
    }

    @Override
    public void delete(Long id) {
        if(id != null){
            //先删除子菜单
            systemmenuMapper.deleteChildMenu(id);
            //在删除自己
            systemmenuMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public Systemmenu get(Long id) {
        return systemmenuMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Systemmenu> list() {
        return systemmenuMapper.selectAll();
    }


    @Override
    public List<Systemmenu> query(SystemMenuQueryObject qo) {
        return systemmenuMapper.queryForMenu(qo);
    }


    @Override
    public List<Systemmenu> getParentMenus(Long parentId) {
        //定义集合存储菜单
        List<Systemmenu> menus = new ArrayList<>();
        //因为传入的参数是父菜单的id,所以获取的菜单必定是当前菜单的父菜单信息
        Systemmenu menu = systemmenuMapper.selectByPrimaryKey(parentId);
            //判断获取的菜单是否为空
            while (menu != null){
                menus.add(menu);//不为空添加到集合中
                //继续获取当前菜单的父菜单
                menu = menu.getParent();
            }
        //逆序
        Collections.reverse(menus);
        return menus;
    }

    @Override
    public List<Map<String, Object>> getMenusBySn(String menuSn) {
        Employee currentUser = UserContext.getCurrentUser();
        if(currentUser.getAdmin()){//判断是否是admin,如果是,查看全部的菜单
            List<Map<String, Object>> maps = systemmenuMapper.selectMenusBySn(menuSn);
            return maps;
        }
        //如果不是admin,则根据用户的id和父菜单的sn来获取当前用户拥有的菜单
        return systemmenuMapper.selectMenusBySnAndUserId(menuSn,currentUser.getId());
    }

}
